package com.lm56.web.sys.service;

import com.lm56.web.sys.domain.Catalog;
import com.lm56.web.sys.mapper.CatalogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Kelvin Yeung on 2016/11/30.
 */
@Component
@Transactional
public class CatalogService {


    @Autowired
    CatalogMapper catalogMapper;

    public void insertCatalogs(List<Catalog> catalogs){
        //判断catalog是否合符规则；
        //1.是否存不是1级目录而又没有父节点的;

    }

    public void updateCatalog(Catalog catalog){
        //TODO:判断是否目录是否合符逻辑
        catalogMapper.updateCatalog(catalog);
    }

    public void deleteCatalog(String catCode){
        catalogMapper.deleteCatalogByCode(catCode);
    }


    public List<Catalog> getCatalogTree() {
        List<Catalog> catalogs = catalogMapper.getEnabledCatalog();
        List<Catalog> tree = this.genTree(catalogs);
        return tree;
    }


    private List<Catalog> genTree(List<Catalog> catalogs) {
        List<Catalog> tree = new ArrayList<Catalog>();

        for(Catalog catalog:catalogs){
            if(catalog.getLvl() == 1){
                if(!catalog.getIsLeaf()){
                    catalog.setSubCats(getSubCats(catalog,catalogs));
                }
                tree.add(catalog);
            }
        }

        return tree;
    }


    private List<Catalog> getSubCats(Catalog catalog,List<Catalog> catalogs){
        String catCode = catalog.getCatCode();
        List<Catalog> subCats = new ArrayList<Catalog>();
        for(Catalog tmpCat:catalogs){
            if(tmpCat.getParentCode().equals(catCode)){
                subCats.add(tmpCat);
                if(tmpCat.getIsLeaf()){
                    catalogs.remove(tmpCat);
                }
            }

            if(!tmpCat.getIsLeaf()){
                tmpCat.setSubCats(getSubCats(tmpCat,catalogs));
            }

        }

        return subCats;

    }


}
